package com.joey.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Author hyy
 **/
@Slf4j
public class SemaphoreExample1 {

    private static final int threadCount = 2000;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadCount/500);

        for (int i=0;i<threadCount;i++){
            final int threadNum = i;
            executorService.execute(()->{
                try {
                    //尝试获取许可。当前允许的并发数据是4，超过4个的就丢弃
                    if(semaphore.tryAcquire()){
                        test(threadNum);
                        //释放许可
                        semaphore.release();
                    }
                } catch (InterruptedException e) {
                    log.error("exception",e);
                }
            });
        }
        //

        log.info("finish");
        executorService.shutdown();

    }

    /**
     * 获取许可之后，在这里等待5秒，但是tryAcquire在1秒以后就放弃其他并发线程。
     * @param threadCount
     * @throws InterruptedException
     */
    private static void test(int threadCount) throws InterruptedException {
        Thread.sleep(500);
        log.info("threadCount:{}",threadCount);
    }




}
